package com.liaoban.app.ui.base;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.view.View;

import com.liaoban.app.R;
import com.liaoban.app.api.type.event.LogoutEvent;
import com.liaoban.app.constants.Constant;
import com.liaoban.app.exception.AppException;
import com.liaoban.app.helper.BaseHelper;
import com.liaoban.app.helper.DialogHelper;
import com.liaoban.app.helper.ToastHelper;
import com.liaoban.app.ui.login.LoginActivity;
import com.liaoban.app.ui.login.PhoneLoginActivity;
import com.liaoban.app.util.CommonUtils;
import com.liaoban.app.util.RxUtils;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;

/**
 * Activity基类
 * Created by ybc on 2017/7/5.
 */

public abstract class BaseActivity extends RxAppCompatActivity {

    protected ProgressDialog mRunningDialog;

    // 设置Activity的布局id
    @LayoutRes
    protected abstract int getLayoutResID();

    //此方法中进行View内容的初始化，此时View已经通过注入获取.
    protected abstract void initView(Bundle savedInstanceState);

    Unbinder unbinder;

    //是否使用EventBus,如果使用EventBus,则子类必须要有public的onEvent方法
    private boolean mNeedOnBus;

    protected void setNeedOnBus(boolean needOnBus) {
        mNeedOnBus = needOnBus;
    }

    //用于友盟统计，是否含有fragment
    private boolean hasFragment = false;

    public void setHasFragment(boolean hasFragment) {
        this.hasFragment = hasFragment;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        int layoutResID = getLayoutResID();
        if (layoutResID > 0) {
            setContentView(layoutResID);
        }
        unbinder = ButterKnife.bind(this);
        initView(savedInstanceState);
        if (mNeedOnBus) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onPostCreate(@Nullable Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        if (getWindow() != null) {
            BaseHelper.initSwipeRefreshLayoutColor(getWindow().getDecorView());
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 友盟
        if (!hasFragment) {
            MobclickAgent.onPageStart(getClass().getSimpleName());
        }
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 友盟
        if (!hasFragment) {
            MobclickAgent.onPageEnd(getClass().getSimpleName());
        }
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        if (mNeedOnBus) {
            EventBus.getDefault().unregister(this);
        }
        unbinder.unbind();
        super.onDestroy();
    }

    //用于执行异步任务
    protected <T> void startTask(Observable<T> observable, Consumer<? super T> onNext, Consumer<? super Throwable> onError) {
        observable.compose(bindToLifecycle()).compose(RxUtils.ioToMainTread()).subscribe(onNext, onError, this::onComplete);
    }

    //用于执行异步任务
    protected <T> void startTask(Observable<T> observable, Consumer<? super T> onNext) {
        observable.compose(bindToLifecycle()).compose(RxUtils.ioToMainTread()).subscribe(onNext, this::defOnError, this::onComplete);
    }

    private void onComplete() {
        dismissRunningDialog();
    }

    protected void defOnError(Throwable t) {
        dismissRunningDialog();
        if (t instanceof AppException) {
            ToastHelper.show(this, ((AppException) t).getMsg());
            if (Constant.LOGIN_STATUS == ((AppException) t).getCode()) {
                CommonUtils.logout(this);
                EventBus.getDefault().post(new LogoutEvent());
                startActivity(new Intent(this, LoginActivity.class));
                finish();
            }
        } else {
            ToastHelper.show(this, t.getMessage());
        }
    }

    protected void showRunningDialog() {
        if (mRunningDialog == null) {
            mRunningDialog = DialogHelper.getProgressDialog(this, R.string.running);
        } else {
            mRunningDialog.setMessage(getString(R.string.running));
        }
        mRunningDialog.show();
    }

    protected void showRunningDialog(int resId) {
        if (mRunningDialog == null) {
            mRunningDialog = DialogHelper.getProgressDialog(this, resId);
        } else {
            mRunningDialog.setMessage(getString(resId));
        }
        mRunningDialog.show();
    }

    protected void dismissRunningDialog() {
        if (mRunningDialog != null && mRunningDialog.isShowing()) {
            mRunningDialog.dismiss();
        }
    }

    /**
     * 设置距离顶部距离
     *
     * @param contentView
     */
    protected void setMarginTop(View contentView, int num) {
        contentView.setPadding(0, num, 0, 0);
    }

    /**
     * 利用反射获取状态栏高度
     *
     * @return
     */
    protected int getStatusBarHeight() {
        int result = 0;
        //获取状态栏高度的资源id
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 后退通知
     */
    public interface BackHandledInterface {
        public abstract void setSelectedFragment(BackHandledFragment selectedFragment);
    }
}
